import tkFileDialog as tk
import numpy as np
import pylab as lab
import pyfits 
#import set_cord 
from glob import glob
import os,csv,math,shutil,sys
import asciidata,operator,copy,itertools
import scipy.spatial as spatial
import scipy.ndimage as ndimage #can use for filters (high/low pass)
from reduice import*
import divide
import tkMessageBox

def SubtractBias(path=None,outdir=None):
 '''(str,str) -> None 
   Opens the various directories(Dark,Flat and Light) and prepares  subtracts the  bais form all the fits files '''

 bias_dic,bias_hdr = get_bias(path+'/bias',outdir=path+'/Reduced')
 bias 	           =bias_dic.values()[0]
 hdr               =bias_hdr.values()[0]

 dim1_bias         =hdr['NAXIS1']
 dim2_bias         =hdr['NAXIS2']
 
 files=glob(path+'/*')
 
 #fits_files  = [ 'flats' , 'EXHYA' ]
 if path==None:
  path = gui_getdir(title='Please Select FITS Directory')
 
 for fdir in files:
  indir      = glob( fdir + '/*' )
 
  if not os.path.isdir(fdir):
   #print path+ ' is not a directory' 
   continue

  for fit in indir:
   if not (fit.endswith('.fit') or fit.endswith('.fits')) or pyfits.getval(fit,'IMAGETYP')=='Bias Frame':
    #print 'not afits'+fit
    continue

   fits_array, hdr_fit = fromfits( fit,verbose=False )
   dim1_fits       = hdr_fit['NAXIS1']
   dim2_fits       = hdr_fit['NAXIS2']
   if dim1_fits==dim1_bias and dim2_fits==dim2_bias:
    new_array       = fits_array - bias
    
   else:
    print 'arrays not the same sizes'
    continue
    #tkMessageBox.showinfo("Error",'Array not the same size!')
   hdr_fit.add_history(' bias subtracted')
   new_path=fit[fit.rfind('/'):]
   tofits(path+'Reduced/Biased'+ new_path,new_array,hdr_fit)
   
  
def RemoveDarks(path=None): 
 dark_dic,hdr        = get_bias()
 light_dir=glob(path+'/Reduced/Biased/*')

 if path==None:
  path = gui_getdir(title='Please Select FITS Directory')

 #darks=glob(path+'/Reduced/Darked/*')
 darks=dark_dic.getvalues()
 hdr=hdr.values()

 for i in len(darks):
  dark_exptime= hdr[i]['EXPTIME']
  dark_array=darks[i]
  dim1_dark         =hdr[i]['NAXIS1']
  dim2_dark         =hdr[i]['NAXIS2']
  
  
  for fit in light_dir:
   if not (fit.endswith('.fit') or fit.endswith('.fits')):
    print 'not afits'+fit
    continue

   light_exptime=pyfits.getval(fit,'EXPTIME')
   factor=light_exptime/dark_exptime
   fits_array, hdr = fromfits( fit ,verbose=False)
   dim1_fits       = hdr['NAXIS1']
   dim2_fits       = hdr['NAXIS2']

   if dim1_fits==dim1_bias and dim2_fits==dim2_bias:
    new_array       = fits_array - dark_array*factor

   else: 
    print 'arrays not the same sizes'
    #tkMessageBox.showinfo("Error",'Array not the same size!')

   hdr.add_history(' bias subtracted')
   new_path=fit[fit.rfind('/'):]
   tofits(path+'Reduced/Darked'+ new_path,new_array,hdr)
   
def RemoveFlat(path=None):
 if path==None:
  path= gui_getdir(title='Please Select fits Directory')
 
 flats_dic,hdr =get_flats(path=path+'/flats', outdir=path+'/Reduced/')
 lights=glob(path+'/Reduced/Darked/*')

 if len(lights)==0: #no darks
  lights=glob(path+'/Reduced/Biased/*') #use biased
 #lights=glob(path+'EXHYA/*')

 lights=get_fits_type(lights,'light') #remove flat only on lights
 flats      = flats_dic.values()  
 flit       = flats_dic.keys()  
 hdr        = hdr.values()

 for i in range(len(flats)):
  Filter=   flit[i]
  dim1_flat         =hdr[i]['NAXIS1']
  dim2_flat         =hdr[i]['NAXIS2']
  
  for light in lights:
   light_filt=str(pyfits.getval(light,'FILTER'))
   
   if Filter == light_filt:
    flat_arry        = flats[i]
   
    light_arry , hdr = fromfits(light,verbose=False)
    
    dim1_fits       = hdr['NAXIS1']
    dim2_fits       = hdr['NAXIS2']
    
    if dim1_fits==dim1_flat and dim2_fits==dim2_flat:
     light_arry     /=(flat_arry)
     light_arry	    *=flat_arry.max() 
    else:
     print 'arrays not the same sizes'

    new_path=light[light.rfind('/'):]
    hdr.add_history(' flat divided')
    tofits(path+'Reduced/Flatfielded'+new_path,light_arry,hdr)
    lights.pop(lights.index(light)) 
  
def main():
 path      = gui_getdir( title = 'Please Select Fits Directory')
 if not path:
  raise ValueError( 'Must specify directory where files are.' )
 if not path.endswith( '/' ):
  path      += '/'

 sort=raw_input('Are the raw fits files sorted into their different directories (eg flats,bias darks...) y/n\n')

 if sort.lower()=='n':
  divide.div(path)

 divide.products(path)
 SubtractBias(path=path)
 RemoveFlat(path=path)

if __name__ == "__main__":
	main()
 

 
 
